﻿using HslCommunication;
using HslCommunication.Profinet.Omron;
using IniReadWrite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VisionRoc.Core
{
    public class OmronFinsTcp
    {
        string Path = string.Empty;
        public OmronFinsTcp(string _Path)
        {
            //判断文件路径是否存在
            if (!Directory.Exists(_Path))
            {
                Directory.CreateDirectory(_Path);
            }
            Path = _Path + "\\OmronFinsUdp.ini";
            if (File.Exists(Path))
            {
                ReadParameter();
                OpenOmronFinsTCP();
            }
            else
            {
                Global.AddLogInfoEvent(LogLevel.Info, $"未找到 与欧姆龙PLC FinsTCP通信参数文件");
            }
        }

        public OmronFinsNet PLC = new OmronFinsNet();

        public int IsConnect;

        public string IP = string.Empty;

        public int Port;

        public void OpenOmronFinsTCP()
        {
            try
            {
                PLC = new OmronFinsNet();
                PLC.IpAddress = IP;
                PLC.Port = Port;
                PLC.ConnectTimeOut = 2000;     // 连接超时，单位毫秒
                PLC.ReceiveTimeOut = 5000;     // 接收超时，单位毫秒
                PLC.DA2 = 0;
                PLC.ByteTransform.DataFormat = HslCommunication.Core.DataFormat.CDAB;
                PLC.ByteTransform.IsStringReverseByteWord = true;
                OperateResult connect = PLC.ConnectServer();
                if (connect.IsSuccess)
                {
                    Global.AddLogInfoEvent(LogLevel.OK, $"PLC 通讯连接成功 IP:{   PLC.IpAddress},Port:{ PLC.Port}");
                    IsConnect = 1;
                }
                else
                {
                    Global.AddLogInfoEvent(LogLevel.Error, $"PLC 通讯连接失败 IP:{   PLC.IpAddress},Port:{ PLC.Port}");
                    IsConnect = 2;
                }
            }
            catch
            {
                IsConnect = 2;
                Global.AddLogInfoEvent(LogLevel.Error, "PLC 通讯连接异常");
            }
        }

        /// <summary>
        /// 读取参数
        /// </summary>
        public void ReadParameter()
        {
            IP = IniAPI.INIGetStringValue(Path, "IP", "IP", "0");
            Port = Convert.ToInt32(IniAPI.INIGetStringValue(Path, "Port", "Port", "0"));
        }


        /// <summary>
        /// 保存参数
        /// </summary>
        public void WriteParameter()
        {
            IniAPI.INIWriteValue(Path, "IP", "IP", IP);
            IniAPI.INIWriteValue(Path, "Port", "Port", Port.ToString());
        }

    }
}
